package cn.king.springframework.context.support;

import cn.king.springframework.beans.BeanException;
import cn.king.springframework.beans.factory.ConfigurableListableBeanFactory;
import cn.king.springframework.beans.factory.config.BeanFactoryPostProcessor;
import cn.king.springframework.beans.factory.config.BeanPostProcessor;
import cn.king.springframework.context.ApplicationEvent;
import cn.king.springframework.context.ApplicationListener;
import cn.king.springframework.context.ConfigurableApplicationContext;
import cn.king.springframework.context.event.ApplicationEventMulticaster;
import cn.king.springframework.context.event.ContextClosedEvent;
import cn.king.springframework.context.event.ContextRefreshedEvent;
import cn.king.springframework.context.event.SimpleApplicationEventMulticaster;
import cn.king.springframework.core.io.DefaultResourceLoader;

import java.util.Collection;
import java.util.Map;

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
    public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Override
    public Object getBean(String name) throws BeanException {
        return getBeanFactory().getBean(name);
    }

    @Override
    public Object getBean(String name, Object... args) {
        return getBeanFactory().getBean(name,args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requireType) {
        return getBeanFactory().getBean(name,requireType);
    }

    @Override
    public <T> Map<String, T> getBeanOfType(Class<T> type) throws BeanException {
        return getBeanFactory().getBeanOfType(type);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public void refresh() throws BeanException {
        //1、创建BeanFactory,并加载BeanDefinition
        refreshBeanFactory();
        //2、获取BeanFactory
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        //3、 添加 ApplicationContextAwareProcessor，让继承自 ApplicationContextAware 的 Bean 对象都能感知所属的 ApplicationContext
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
        //4、在 Bean 实例化之前，执行 BeanFactoryPostProcessor (Invoke factory processors registered as beans in the context.)
        invokeBeanFactoryPostProcessors(beanFactory);
        //5、BeanPostProcessor 需要提前于其他 Bean 对象实例化之前执行注册操作
        registerBeanPostProcessors(beanFactory);
        //6、初始化事件发布者
        initApplicationEventMulticaster();
        // 7. 注册事件监听器
        registryListeners();
        // 8. 提前实例化单例Bean对象
        beanFactory.preInstantiateSingletons();
        //9发布容器刷新完成事件
        finishRefresh();
    }



    private void finishRefresh(){
        publishEvent(new ContextRefreshedEvent(this));

    }

    @Override
    public void publishEvent(ApplicationEvent event) {
        applicationEventMulticaster.multicastEvent(event);

    }

    private void registryListeners(){
        Collection<ApplicationListener> applicationListeners = getBeanOfType(ApplicationListener.class).values();
        for(ApplicationListener listener:applicationListeners){
            applicationEventMulticaster.addApplicationListener(listener);
        }
    }


    private void initApplicationEventMulticaster(){
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registrySingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,applicationEventMulticaster);


    }

    private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory){
        Map<String, BeanFactoryPostProcessor> beanFactoryPostProcessorMap = beanFactory.getBeanOfType(BeanFactoryPostProcessor.class);
        for(BeanFactoryPostProcessor processor:beanFactoryPostProcessorMap.values()){
            processor.postProcessBeanFactory(beanFactory);

        }
    }
    private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory){
        Map<String, BeanPostProcessor> beanPostProcessorMap = beanFactory.getBeanOfType(BeanPostProcessor.class);
        for(BeanPostProcessor processor:beanPostProcessorMap.values()){
            beanFactory.addBeanPostProcessor(processor);
        }
    }

    protected abstract void refreshBeanFactory() throws BeanException;

    protected abstract ConfigurableListableBeanFactory getBeanFactory();


    @Override
    public void registerShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(this::close));

    }

    @Override
    public void close() {
        //发布容器关闭事件
        publishEvent(new ContextClosedEvent(this));
        //执行单例销毁
        getBeanFactory().destroySingletons();
    }




}
